package com.lemon.components.ant.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;


public class ProcessExecutor {
	
	public static String executeOnce(String cmd,String runpath) {
		StringBuilder result = new StringBuilder();
		try {
			String[] cmdA = { "cmd", "/c", cmd };
			Process process = Runtime.getRuntime().exec(cmdA,null,new File(runpath));
			try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(),"utf-8"), 1024);){
				String tmp;
				while((tmp = br.readLine())!=null){
					result.append(tmp);
					result.append("\n");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			process.waitFor();
			return result.toString();
		} catch (Exception e) {
			return e.getMessage();
		}
	}
	
	public static BufferedReader build(String cmd) {
		try {
			String[] buildCommand = { "cmd", "/c", cmd };
			Process process = new ProcessBuilder(buildCommand).redirectErrorStream(true).start();
			return new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void main(String[] args) {
		BufferedReader br = ProcessExecutor.build("ping -t 127.0.0.1");
		String tmp;
		try {
			while((tmp = br.readLine())!=null){
				System.out.println(tmp);
			}
		} catch (IOException e) {
		}
	}
}
